package com.mapfinal.render.style;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mapfinal.MapfinalObject;
import com.mapfinal.converter.JsonStore;
import com.mapfinal.kit.StringKit;

/**
 * The UserStyle element defines styling for a layer.
 * @author yangyong
 *
 */
public class Style implements MapfinalObject, JsonStore {

	/**
	 * The name of the style, used to reference it externally. (Ignored for catalog styles.)
	 */
	private String name;
	private String title;
	private String description;
	private List<FeatureTypeStyle> featureTypes;

	public Style() {
		setFeatureTypes(new ArrayList<FeatureTypeStyle>());
	}

	@Override
	public void fromJson(JSONObject jsonObject) {
		// TODO Auto-generated method stub
		name = jsonObject.containsKey("name") ? jsonObject.getString("name") : name;
		title = jsonObject.containsKey("title") ? jsonObject.getString("title") : title;
		description = jsonObject.containsKey("description") ? jsonObject.getString("description") : description;
		if (jsonObject.containsKey("featureTypes")) {
			featureTypes.clear();
			JSONArray jsonArray = jsonObject.getJSONArray("featureTypes");
			for (int i = 0; i < jsonArray.size(); i++) {
				FeatureTypeStyle rule = new FeatureTypeStyle();
				rule.fromJson(jsonArray.getJSONObject(i));
				featureTypes.add(rule);
			}
		}
	}

	@Override
	public JSONObject toJson() {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject();
		if(StringKit.notBlank(name)) json.put("name", name);
		if(StringKit.notBlank(title)) json.put("title", title);
		if(StringKit.notBlank(description)) json.put("description", description);
		if (featureTypes.size() > 0) {
			JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < featureTypes.size(); i++) {
				FeatureTypeStyle rule = featureTypes.get(i);
				jsonArray.add(rule.toJson());
			}
			json.put("featureTypes", jsonArray);
		}
		return json;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		featureTypes.clear();
	}

	public List<FeatureTypeStyle> getFeatureTypes() {
		return featureTypes;
	}

	public void setFeatureTypes(List<FeatureTypeStyle> featureTypes) {
		this.featureTypes = featureTypes;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}
